package com.mcintyret.site.journal.database;

import com.mcintyret.site.journal.*;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;

import javax.sql.DataSource;

/**
 * User: mcintyret2
 * Date: 29/03/2012
 */

@Configuration
public class JournalDatabaseConfig {

    @Value("${common.database.driverClassName}")
    private String databaseDriverClassName;
    @Value("${journal.database.url}")
    private String databaseUrl;
    @Value("${journal.database.username}")
    private String databaseUsername;
    @Value("${journal.database.password}")
    private String databasePassword;


    @Bean
    public DataSource journalDataSource() {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriverClassName);
        basicDataSource.setUrl(databaseUrl);
        basicDataSource.setUsername(databaseUsername);
        basicDataSource.setPassword(databasePassword);
        return basicDataSource;
    }

    @Bean
    public SessionFactory journalSessionFactory() {
        return new LocalSessionFactoryBuilder(journalDataSource())
                .addAnnotatedClasses(JournalFamily.class, Journal.class, TextEntry.class, Timeseries.class,
                                     Datapoint.class)
                .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
                .setProperty("hibernate.current_session_context_class", "thread")
                .setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory")
//                .setProperty("hibernate.show_sql", "true")
                .buildSessionFactory();
    }

}
